/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.api.security.key;

import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.OctetKeyPair;
import com.nimbusds.jose.jwk.OctetSequenceKey;
import com.nimbusds.jose.jwk.RSAKey;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 凭证处理器
 *
 * @author zeng
 */
public interface OAuth2JWKRepository {
  /**
   * 验证jwk
   *
   * @param jwk jwk
   * @return jwk
   */
  default JWK verificationJWK(JWK jwk) {
    String keyID = jwk.getKeyID();
    Date issueTime = jwk.getIssueTime();
    if (keyID == null && issueTime != null) {
      return jwk;
    }
    if (keyID == null) {
      keyID = UUID.randomUUID().toString();
    }
    if (issueTime == null) {
      issueTime = new Date();
    }
    KeyType keyType = jwk.getKeyType();
    if (keyType.equals(KeyType.RSA)) {
      jwk = new RSAKey.Builder((RSAKey) jwk).issueTime(issueTime).keyID(keyID).build();
    } else if (keyType.equals(KeyType.EC)) {
      jwk = new ECKey.Builder((ECKey) jwk).issueTime(issueTime).keyID(keyID).build();
    } else if (keyType.equals(KeyType.OCT)) {
      jwk =
          new OctetSequenceKey.Builder((OctetSequenceKey) jwk)
              .issueTime(issueTime)
              .keyID(keyID)
              .build();
    } else if (keyType.equals(KeyType.OKP)) {
      jwk = new OctetKeyPair.Builder((OctetKeyPair) jwk).issueTime(issueTime).keyID(keyID).build();
    }
    return jwk;
  }

  List<JWK> findJWKs();

  void delete(String id);

  void save(JWK jwk);

  JWK findById(String keyId);
}
